package storage

import (
	"codeless/config"
	models "codeless/model"
	"codeless/utils"
	"errors"
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"mime/multipart"
	"os"
	"path/filepath"
	"strings"
)

type OssStorage struct {
}

var aliOssClient *oss.Client

func init() {
	fs := config.GetAppConfig().Fs
	if fs.Storage == "oss" && fs.Oss.Id != "" {
		client, err := oss.New(fs.Oss.RawUrl, fs.Oss.Id, fs.Oss.Key)
		if err != nil {
			config.LoggerErr("oss init", err)
		} else {
			aliOssClient = client
		}
	}

}

func (c *OssStorage) Upload(fh *multipart.FileHeader) (*models.RestOss, error) {
	if aliOssClient == nil {
		return nil, errors.New("上传失败，客户端未初始化")
	}
	fs := config.GetAppConfig().Fs
	bucket, err := aliOssClient.Bucket(fs.Oss.Bucket)
	if err != nil {
		return nil, err
	}
	file, fer := fh.Open()
	if fer != nil {
		return nil, errors.New("上传失败，文件打开失败")
	}
	fileSuffix := strings.ToLower(filepath.Ext(fh.Filename))
	rId := utils.NewId()
	if fileSuffix == "" {
		fileSuffix = ".jpg"
	}
	name := rId + fileSuffix
	if fs.Oss.Dir != "" {
		name = fs.Oss.Dir + "/" + name
	}
	err = bucket.PutObject(name, file)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	burl := fs.Oss.RawUrl + "/" + name
	if fs.Oss.Cdn != "" {
		burl = fs.Oss.Cdn + "/" + name
	}
	resp := models.RestOss{
		Code:       0,
		Message:    "",
		Id:         rId,
		ObjectName: name,
		Url:        burl,
	}
	return &resp, nil
}

func (c *OssStorage) UploadLocal(filePath string) (*models.RestOss, error) {
	if aliOssClient == nil {
		return nil, errors.New("上传失败，客户端未初始化")
	}
	fs := config.GetAppConfig().Fs
	bucket, err := aliOssClient.Bucket(fs.Oss.Bucket)
	if err != nil {
		return nil, err
	}
	fileSuffix := strings.ToLower(filepath.Ext(filePath))
	rId := utils.NewId()
	if fileSuffix == "" {
		fileSuffix = ".jpg"
	}
	name := rId + fileSuffix
	if fs.Oss.Dir != "" {
		name = fs.Oss.Dir + "/" + name
	}
	err = bucket.PutObjectFromFile(name, filePath)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	burl := fs.Oss.RawUrl + "/" + name
	if fs.Oss.Cdn != "" {
		burl = fs.Oss.Cdn + "/" + name
	}
	miniResp := models.RestOss{
		Code:       0,
		Message:    "",
		Id:         rId,
		Url:        burl,
		ObjectName: name,
	}
	return &miniResp, nil
}
func (c *OssStorage) DelOss(objectName string) error {
	if aliOssClient == nil {
		return errors.New("上传失败，客户端未初始化")
	}
	fs := config.GetAppConfig().Fs
	bucket, err := aliOssClient.Bucket(fs.Oss.Bucket)
	if err != nil {
		return err
	}
	return bucket.DeleteObject(objectName)
}
